﻿using System;
using System.IO;
using System.Xml.Serialization;
using Startup.Base.Exceptions;

namespace Startup.Base.Xml
{
	public class StoragedItem
	{
		private string _sourcePath = string.Empty;

		public bool HasSourceFile
		{
			get { return !string.IsNullOrEmpty(_sourcePath); }
		}

		public void Save()
		{
			if (string.IsNullOrEmpty(_sourcePath))
				throw new IncorrectStateException("This instance hasn't been loaded from file and cannot be saved by this method.");

			SaveAs(_sourcePath);
		}

		public void SaveAs(string filePath)
		{
			if (string.IsNullOrEmpty(filePath))
				throw new ArgumentNullException("filePath");

			var serializer = new XmlSerializer(GetType());
			
			using (FileStream stream = File.Create(filePath))
			{
				serializer.Serialize(stream, this);
			}

			_sourcePath = filePath;
		}

		public static T Load<T>(string filePath)
		{
			if (string.IsNullOrEmpty(filePath))
				throw new ArgumentNullException("filePath");

			var serializer = new XmlSerializer(typeof(T));

			using (FileStream stream = File.OpenRead(filePath))
			{
				var result = (T)serializer.Deserialize(stream);

				if (result is StoragedItem)
					(result as StoragedItem)._sourcePath = filePath;

				return result;
			}
		}
	}
}
